import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import createStaticRoutes from './routes'
import { store } from '@/store'
import { ElMessage } from 'element-plus'
export const staticRoutes = createStaticRoutes()

const router = createRouter({
  history: createWebHashHistory(),
  scrollBehavior: () => ({ top: 0 }),
  routes: staticRoutes
})

router.beforeEach((to, from, next) => {
  if (store.state.permission.asyncRoutes.length === 0) {
    return store
      .dispatch('permission/getFlows')
      .then((routes: RouteRecordRaw[]) => {
        routes?.forEach(route => router.addRoute(route))
        next(to)
      })
      .catch(err => {
        console.log(err)
        ElMessage.error('获取路由接口报错，请检查环境')
        next()
      })
  }
  next()
})

export default router
